package com.stkouyu;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.stkouyu.entity.EvaluateResult;
import com.stkouyu.entity.EvaluateScores;
import com.stkouyu.entity.EvaluateWord;
import com.stkouyu.entity.LgEvaluateObj;
import com.stkouyu.xiansheng.SSoundManager;
import com.stkouyu.xiansheng.entity.ResultDetails;
import com.stkouyu.xiansheng.entity.SoundResult;
import com.xs.SingEngine;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by pengmi on 2018/7/31.
 * Description:对SkEgnManager 进行二次封装
 */


public class LancooSkEgnManager {

    private final int MST_OUTTIME=10;
    private static LancooSkEgnManager lancooSkEgnManager;
//    private OnLancooRecordListener onLancooRecordListener;
    private OnLancooRecordListener onLancooRecordListener;
    private WeakReference<Context> mContext;
    private String recordUrl;
    private int volume;
    private SingEngine mSingEngine;


    private LancooSkEgnManager(Context mContext){
        this.mContext=new WeakReference<>(mContext);
    }

    public static LancooSkEgnManager getInstance(Context mContext){
        if(lancooSkEgnManager==null){
            lancooSkEgnManager=new LancooSkEgnManager(mContext.getApplicationContext());
        }
        return lancooSkEgnManager;
    }

    public void startRecord(String content,String url ,OnLancooRecordListener onLancooRecordListener){

        this.onLancooRecordListener=onLancooRecordListener;
        mHandler.removeMessages(MST_OUTTIME);
        String recordName= UUID.randomUUID()+".wav";
        String recordFilePath=getTempRecordFilePath();
        recordUrl = recordFilePath+"/"+recordName;
        Log.e("eeeee","语音评测url："+ recordUrl);
        SSoundManager.getInstance(mContext.get()).startRecord(content,recordUrl,mHandler,
                onLancooRecordListener);
    }

    public void stopRecord(boolean isShowScore){
        volume=0;
        Log.e("aaaaaaaaa","stopRecord"+isShowScore);
        if(!isShowScore){
            SSoundManager.getInstance(mContext.get()).cancelRecord();
            mHandler.removeMessages(MST_OUTTIME);
        }else{
            SSoundManager.getInstance(mContext.get()).stopRecord();
            mHandler.sendEmptyMessageDelayed(MST_OUTTIME,30000);
        }
    }




    public interface OnLancooRecordListener{
        void onRecordStart();
        void onRecording(int vad_status, int sound_intensity);
        void onRecordEnd(int grade, String url, LgEvaluateObj skegnObj);
        void onRecordError(String error);
        void onRecordStop();
    }

    private String getTempRecordFilePath(String recorderFileName){
        File targetDir = new File(Environment.getExternalStorageDirectory(),
                "Android/data/" + mContext.get().getApplicationInfo().packageName + "/files/record/klg");
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        return targetDir.getPath()+"/"+recorderFileName+".wav";
    }

    private String getTempRecordFilePath(){
        File targetDir = new File(Environment.getExternalStorageDirectory(),
                "Android/data/" + mContext.get().getApplicationInfo().packageName + "/files/record/klg");
        if (!targetDir.exists()) {
            boolean isCreate=targetDir.mkdirs();
        }
        return targetDir.getPath();
    }



    public void initSkegn(final Context mContext){
        SSoundManager.getInstance(mContext).initSSoundEngine();

    }



    private Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            mHandler.removeMessages(MST_OUTTIME);
            if(msg.what==MST_OUTTIME){
                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecordError("out time!");
                }
                if(mContext!=null){
                    SSoundManager.getInstance(mContext.get()).cancelRecord();
                    Log.e("aaaa","重新进行评测初始化。。。");
                }
            }else if(msg.what==100){
                SoundResult soundResult= (SoundResult) msg.obj;
                if(onLancooRecordListener!=null){
                    LgEvaluateObj lgEvaluateObj=new LgEvaluateObj();
                    List<EvaluateWord> list=new ArrayList<>();
                    EvaluateResult evaluateResult=new EvaluateResult();
                    lgEvaluateObj.setResult(evaluateResult);
                    for (ResultDetails details:soundResult.getDetails()){
                        EvaluateWord evaluateWord=new EvaluateWord();
                        evaluateWord.setWord(details.getText());
                        EvaluateScores evaluateScores=new EvaluateScores();
                        evaluateScores.setOverall((int) details.getScore());
                        evaluateWord.setScores(evaluateScores);
                        list.add(evaluateWord);
                    }
                    evaluateResult.setWords(list);
                    if(onLancooRecordListener!=null){
                        onLancooRecordListener.onRecordEnd((int) soundResult.getOverall(),soundResult.getRecordUrl(),lgEvaluateObj);
                    }

                }
            }else if(msg.what==101){
                String error= (String) msg.obj;
                Log.e("123","error:"+error);

                int arg1 = msg.arg1;
                if((arg1==41030||arg1==70017)&&mContext!=null&&mContext.get()!=null){
                    initSkegn(mContext.get());
                }
                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecordError(arg1+"");
                }
            }else if(msg.what==105){
                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecordStart();
                }
            }else if(msg.what==110){
                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecording(0,msg.arg1);
                }
            }else if(msg.what==109){
                if(onLancooRecordListener!=null){
                    onLancooRecordListener.onRecordStop();
                }
            }
            return false;
        }
    });

    public float getVolume(){
        if(volume==0){
            return SSoundManager.getInstance(mContext.get()).getVolume();
        }
        return volume;
    }


}
